package com.basic.library.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;


/**
 * @author jiangyun
 * @version 创建时间：2017/10/27 11:25
 * ViewPager 嵌套ViewPager 也可滑动
 */
public class MViewPager extends ViewPager {
    private boolean isCanScroll = true;

    public MViewPager(Context context) {
        super(context);
    }

    public MViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        try {
            return isCanScroll && super.onInterceptTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        try {
            return isCanScroll && super.onTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
//        if (x > ScreenUtils.getWidth() - 60)
//            return super.canScroll(v, checkV, dx, x, y);
        if (v.getClass().getName().equals("com.amap.api.maps.MapView")) {
            return true;
        }
        if (v.getClass().getName().equals("com.f1reking.signatureview.SignatureView")) {
            return true;
        }
        if (v.getClass().getName().equals("com.github.mikephil.charting.charts.LineChart")) {
            return true;
        }
        if (v != this && v instanceof ViewPager) {
            PagerAdapter pagerAdapter = ((ViewPager) v).getAdapter();
            if (pagerAdapter != null) {
                int currentItem = ((ViewPager) v).getCurrentItem();
                int countItem = pagerAdapter.getCount();
                if ((currentItem == (countItem - 1) && dx < 0) || (currentItem == 0 && dx > 0)) {
                    return false;
                }
            }
            return true;
        }
        return super.canScroll(v, checkV, dx, x, y);
    }

    public void setCanScroll(boolean isCanScroll) {
        this.isCanScroll = isCanScroll;
    }
}
